package cc.linker.steplink.crm.merchant.controller.acs;


import cc.linker.steplink.crm.commons.TradeTypeConstants;
import cc.linker.steplink.crm.commons.model.PcUserInfo;
import cc.linker.steplink.crm.commons.service.CommonsService;
import cc.linker.steplink.crm.commons.utils.NumberUtils;
import cc.linker.steplink.crm.merchanth5.commons.UserInfoUtil;
import cc.linker.steplink.crm.merchant.service.MallBoomBackService;
import cc.linker.steplink.crm.merchant.service.acs.MerchantInfoService;
import cc.linker.steplink.crm.merchant.service.acs.XbMerchantService;
import cc.linker.steplink.crm.merchanth5.service.MaiBaoLaService;
import cc.linker.steplink.crm.merchanth5.service.MallBoomService;
import cc.linker.steplink.crm.merchanth5.service.acs.MerchantSalerService;
import cc.linker.steplink.crm.merchanth5.service.acs.MerchantWalletService;
import cc.linker.steplink.crm.response.GlobalException;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;


/**
 * 商家信息
 * By: hhj
 */

@Slf4j
@RestController
@RequestMapping("acs/merchantinfo")
public class MerchantInfoController {


    @Autowired
    private MerchantInfoService merchantInfoService;

    @Autowired
    private MerchantSalerService merchantSalerService;

    @Autowired
    private MerchantWalletService merchantWalletService;

    @Autowired
    private MallBoomBackService mallBoomBackService;

    @Autowired
    private MaiBaoLaService maiBaoLaService;

    @Autowired
    private XbMerchantService xbMerchantService;

    @Autowired
    private CommonsService commonsService;

    @Autowired
    private MallBoomService mallBoomService;
    @Autowired
    private UserInfoUtil userInfoUtil;
    /**
     * 商家信息首页
     *
     * @return
     */
    @GetMapping("/getinfo")
    public Map<String, Object> getInfo(HttpServletRequest request) {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        Map<String, Object> param = new HashMap<>();
        String orgId = userinfo.getOrgId();
        String adminId = userinfo.getAdminId();
        Boolean ifSales = userinfo.getSaler();
        String createTime = "";
        param.put("orgId", orgId);
        Integer payMode = userinfo.getPayMode();
        if (ifSales) {
            // 联盟商家
            String customerId = merchantInfoService.getCustomerIdByAdminId(adminId);
            param.put("customerId", customerId);
            param.put("type", "2");
            Map<String, Object> cInfo = merchantInfoService.getInfoByCid(customerId);
            createTime = cInfo.getOrDefault("createTime", "").toString();
        } else {
            // 大麦用户
            param.put("type", "1");
            Map<String, Object> oInfo = merchantInfoService.getInfoByOid(orgId);
            createTime = oInfo == null ? "" : oInfo.get("createTime").toString();
        }
        Map<String, Object> result = merchantInfoService.getDetail(param);
        if (result == null) {
            Map<String, Object> temp = new HashMap<>();
            temp.put("storeLogo", "");
            temp.put("storeName", "");
            temp.put("storeContent", "");
            temp.put("touchPhone", "");
            temp.put("touchMobilePhone", "");
            temp.put("touchProvince", "");
            temp.put("touchCity", "");
            temp.put("touchRegion", "");
            temp.put("touchAddress", "");
            temp.put("servicePhone", "");
            temp.put("serviceMobilePhone", "");
            temp.put("returnProvince", "");
            temp.put("returnCity", "");
            temp.put("returnRegion", "");
            temp.put("returnAddress", "");
            temp.put("returnMobilePhone", "");
            temp.put("remindPhone", "");
            result = temp;
        }

        if (!ifSales) {
            // 大麦 获取平台支付 公众号授权
            result.put("publicStatus", 0);
            if (payMode == 2 || payMode == 3) {
                // 通联模式
                String platFormId = merchantInfoService.getPlatForm(orgId);
                result.put("payStatus", StringUtils.isEmpty(platFormId) ? 0 : 1);
            } else {
                // 微信模式
                Boolean payStatus = merchantInfoService.getPayStatus(orgId);
                result.put("payStatus", payStatus == null ? 0 : 1);
            }
        }
        //商家认证 状态
        String busCert = merchantInfoService.getBusCert(param);
        //组装结果返回
        result.put("busCert", busCert == null ? 0 : Integer.parseInt(busCert));
        result.put("createTime", createTime);

        return result;
    }

    @PostMapping("/saveinfo")
    public void saveInfo(@RequestBody Map<String, Object> params,HttpServletRequest request) throws Exception {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        String orgId = userinfo.getOrgId();
        params.put("orgId", orgId);
        String adminId = userinfo.getAdminId();
        Boolean ifSales = userinfo.getSaler();
        params.put("customerType", 1);
        if (ifSales) {
            // 联盟商家
            String customerId = merchantInfoService.getCustomerIdByAdminId(adminId);
            params.put("customerId", customerId);
            params.put("customerType", 2);
        }
        merchantInfoService.saveInfo(params);
    }


    /**
     * 判断当前账户是否开通中金支付
     *
     * @return
     */
    @GetMapping("/ifacs")
    public Map<String, Object> ifAcsAccount(HttpServletRequest request) {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        Map<String, Object> result = new HashMap<>();
        result.put("payMode", userinfo.getPayMode());
        result.put("ifSales", userinfo.getSaler());
        return result;
    }

    /**
     * 获取商家认证信息 根据customerId 和 orgId
     *
     * @param session
     * @return
     */
    @GetMapping("/getmerchantinfo")
    public Map<String, Object> getMerchantInfo(String id, HttpServletRequest request) throws Exception {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        Map<String, Object> param = new HashMap<>();
        String adminId = userinfo.getAdminId();
        //判断是否小B
        Boolean saler = userinfo.getSaler();
        String type = "1";
        if (saler) {
            //取出customerid  用于区分是否是联盟商家
            String customerId = merchantInfoService.getCustomerIdByAdminId(adminId);
            param.put("customerId", customerId);
            type = "2";
        }
        String orgId = userinfo.getOrgId();
        param.put("orgId", orgId);
        param.put("type", type);
        param.put("id", id);
        return merchantInfoService.getMerchantInfo(param);
    }

    /**
     * 保存主体信息
     *
     * @param params
     * @param session
     * @return
     */
    @PostMapping("/savemain")
    public Map<String, Object> saveMainPart(@RequestBody Map<String, Object> params,HttpServletRequest request) throws Exception {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        String orgId = userinfo.getOrgId();
        String adminId = userinfo.getAdminId();
        //判断是否小B
        Boolean saler = userinfo.getSaler();
        String type = "1";
        if (saler) {
            //取出customerid  用于区分是否是联盟商家
            String customerId = merchantInfoService.getCustomerIdByAdminId(adminId);
            if (customerId == null || StringUtil.isEmpty(customerId)) {
                throw GlobalException.build("您还不是联盟商家，请联系开通");
            }
            params.put("customerId", customerId);
            type = "2";
        }
        params.put("orgId", orgId);
        params.put("adminId", adminId);
        params.put("type", type);
        //如果是新增step是2 ； 更新则不修改step
        if (!params.containsKey("id") || StringUtil.isEmpty(params.get("id").toString())) {
            params.put("step", 2);
        }
        return merchantInfoService.saveMerchantInfo(params);
    }

    /**
     * 保存企业法人
     *
     * @param params
     * @param session
     * @return
     */
    @PostMapping("/savelegal")
    public Map<String, Object> saveLegalInfo(@RequestBody Map<String, Object> params, HttpServletRequest request) throws Exception {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        String orgId = userinfo.getOrgId();
        String adminId = userinfo.getAdminId();
        if (!params.containsKey("id") || StringUtil.isEmpty(params.get("id").toString())) {
            throw GlobalException.build("缺少参数id");
        }
        params.put("orgId", orgId);
        params.put("adminId", adminId);
        params.put("step", 3);
        return merchantInfoService.saveMerchantInfo(params);
    }

    /**
     * 提交审核
     *
     * @return
     */
    @PostMapping("/submitaudit")
    public Boolean submitAudit(@RequestBody Map<String, Object> params, HttpServletRequest request) throws Exception {
        if (!params.containsKey("id") || StringUtil.isEmpty(params.get("id").toString())) {
            throw GlobalException.build("缺少参数id");
        }
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        String adminId = userinfo.getAdminId();
        String orgId = userinfo.getOrgId();
        params.put("checkStatus", "1");
        params.put("orgId", orgId);
        params.put("adminId", adminId);
        return merchantInfoService.submitAudit(params);
    }


    /**
     * 清退加盟代理
     * @param param
     * @param session
     */
    @PostMapping("/promoterRetreat")
    public void promoterRetreat(@RequestBody Map<String, Object> param, HttpServletRequest request){
        if(StringUtils.isEmpty(param.get("customerId"))){
            throw GlobalException.build("参数错误");
        }
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        String orgId = userinfo.getOrgId();
        param.put("orgId",orgId);
        Integer promoterCount = mallBoomService.getPromoterCount(param);
        if(promoterCount>0){
            merchantInfoService.promoterRetreat(param);
            merchantSalerService.reducePromoterNum(orgId);
        }else{
            if (merchantSalerService.checkPromoter(orgId)) {
                throw GlobalException.build("达到上限,无法恢复");
            }
            mallBoomService.resavePromoter(param.get("customerId").toString());
            merchantSalerService.addPromoterNum(orgId);
        }


    }

    /**
     * 清退推广员
     * @param param
     * @param session
     */
    @PostMapping("/agentretreat")
    public void agentRetreat(@RequestBody Map<String, Object> param, HttpServletRequest request){
        if(StringUtils.isEmpty(param.get("customerId"))){
            throw GlobalException.build("参数错误");
        }
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        String orgId = userinfo.getOrgId();
        param.put("orgId",orgId);
        Integer agentCount = mallBoomService.getAgentCount(param);
        if(0 == agentCount){
            throw GlobalException.build("参数错误");
        }
        String agentStatus = mallBoomService.getAgentCountStatus(param.get("customerId").toString());
        if("0".equals(agentStatus)){
            param.put("agentStatus","1");
            merchantInfoService.resaveAgent(param);
            merchantSalerService.reduceAgentNum(orgId);
        }else{
            if (merchantSalerService.checkAgent(orgId)) {
                throw GlobalException.build("达到上限,无法恢复");
            }
            param.put("agentStatus","0");
            merchantInfoService.resaveAgent(param);
            merchantSalerService.addAgentNum(orgId);
        }


    }

    //导出加盟代理
    @GetMapping("/exportpromoter")
    public void exportPromoter(@RequestParam(value = "name", defaultValue = "", required = false) String name,
                               @RequestParam(value = "phone", defaultValue = "", required = false) String phone,
                               @RequestParam(value = "startTime", defaultValue = "", required = false) String startTime,
                               @RequestParam(value = "endTime", defaultValue = "", required = false) String endTime,
                               HttpServletRequest request, HttpServletResponse response) throws Exception {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        String orgId = userinfo.getOrgId();
        Map<String, Object> param = new HashMap<>();
        param.put("orgId", orgId);
        param.put("name", name);
        param.put("phone", phone);
        param.put("startTime", startTime);
        param.put("endTime", endTime);
        param.put("export",1);
        List<Map<String, Object>> salerPromoterList = this.promoterData(param);
        String[] key = {"customerName","promoterTime","phone","sonCustomerCount","sonPromoterCount","backFee","settleFee",
                        "customerBalance","getCash","allSonVolume","allSonVolumeSection","promoterVolume","promoterVolumeSection","crossUserTotalVolumeSection"};
        String[] title = {"代理名称","开通时间","手机号","下级数量","下级代理数量","累计返润金额","结算中","可提现金额","已提现金额","累计下级交易额","区间下级交易额","累计下级代理交易额","区间下级代理交易额","区间跨级交易额"};
        String fileName = startTime+"—"+endTime+"代理数据";
        commonsService.excelDownload(salerPromoterList,key,title,fileName,response);
    }
    //导出加盟代理下级数据
    @GetMapping("/exportpromoterson")
    public void exportPromoterSon(@RequestParam(value = "name", defaultValue = "", required = false) String name,
                               @RequestParam(value = "phone", defaultValue = "", required = false) String phone,
                               @RequestParam(value = "startTime", defaultValue = "", required = false) String startTime,
                               @RequestParam(value = "endTime", defaultValue = "", required = false) String endTime,
                                  HttpServletRequest request, HttpServletResponse response) throws Exception {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        String orgId = userinfo.getOrgId();
        Map<String, Object> param = new HashMap<>();
        param.put("orgId", orgId);
        param.put("name", name);
        param.put("phone", phone);
        List<Map<String, Object>> salerPromoterList = merchantInfoService.getSalerPromoterList(param);

        List<Map<String, Object>> tmpList = new ArrayList<>();

        for (Map<String, Object> sp:salerPromoterList){
            List<Map<String, Object>> sCustomerInfoList = merchantInfoService.getsCustomerInfo(sp);
            if(null == sCustomerInfoList || sCustomerInfoList.size()==0){
                continue;
            }
            for(Map<String, Object> ssp:sCustomerInfoList){
                Map<String, Object> tmpMap = new HashMap<>();
                tmpMap.put("customerName",sp.get("customerName"));
                ssp.put("customerId",sp.get("customerId"));
                tmpMap.put("scustomerName",ssp.get("scustomerName"));
                tmpMap.put("sphone",ssp.get("sphone"));
                if(!StringUtils.isEmpty(ssp.get("spromoterTime"))){
                    tmpMap.put("spromoterTime",ssp.get("spromoterTime").toString().substring(0,19));
                }
                tmpMap.put("customerType","promoter".equals(ssp.get("customerType").toString())?"是":"否");
                //累计反润金额
                Object feeBackPre = merchantInfoService.getFeeBack(ssp);
                String feeBack = NumberUtils.fenToYuan(Long.valueOf(feeBackPre.toString()));
                tmpMap.put("feeBack",feeBack);

                //累计交易额
                ssp.put("customerId",ssp.get("scustomerId"));
                Long sonTotalVolume = merchantSalerService.getSonTotalVolume(ssp);
                tmpMap.put("feeDeal",NumberUtils.fenToYuan(sonTotalVolume));

                //结算中
                ssp.put("sett",1);
                ssp.put("customerId",sp.get("customerId"));
                Object settlementPre = merchantInfoService.getFeeDeal(ssp);
                String settlement = NumberUtils.fenToYuan(Long.valueOf(settlementPre.toString()));
                tmpMap.put("settlement",settlement);

                //区间交易额
                ssp.put("customerId",ssp.get("scustomerId"));
                ssp.put("startTime",startTime);
                ssp.put("endTime",endTime);
                Long feeDealPreSection = merchantSalerService.getSonTotalVolume(ssp);
                tmpMap.put("feeDealSection",NumberUtils.fenToYuan(feeDealPreSection));

                tmpList.add(tmpMap);
            }
        }
        String[] key = {"customerName","scustomerName","sphone","spromoterTime","customerType","feeBack","feeDeal","settlement","feeDealSection"};
        String[] title = {"联盟代理名称","下级昵称","下级手机号","绑定时间","是否代理","累计反润金额","累计交易额","结算中","区间交易额"};
        String fileName = startTime+"—"+endTime+"代理下级数据";
        commonsService.excelDownload(tmpList,key,title,fileName,response);
    }

    /**
     * 联盟商家-加盟代理
     *
     * @return
     */
    @GetMapping("/getsalerpromoterlist")
    public PageInfo getSalerPromoterList(@RequestParam(value = "pageIndex", defaultValue = "1", required = false) int pageIndex,
                                         @RequestParam(value = "pageSize", defaultValue = "10", required = false) int pageSize,
                                         @RequestParam(value = "name", defaultValue = "", required = false) String name,
                                         @RequestParam(value = "phone", defaultValue = "", required = false) String phone,
                                         @RequestParam(value = "startTime", defaultValue = "", required = false) String startTime,
                                         @RequestParam(value = "endTime", defaultValue = "", required = false) String endTime,
                                         HttpServletRequest request) {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        PageHelper.startPage(pageIndex, pageSize);
        String orgId = userinfo.getOrgId();
        Map<String, Object> param = new HashMap<>();
        param.put("orgId", orgId);
        param.put("name", name);
        param.put("phone", phone);
        param.put("startTime", startTime);
        param.put("endTime", endTime);
        List<Map<String, Object>> salerPromoterList = this.promoterData(param);
//        assert salerPromoterList != null;
        return new PageInfo<>(salerPromoterList);
    }

    private List<Map<String, Object>> promoterData(Map<String, Object> param){
        List<Map<String, Object>> salerPromoterList = merchantInfoService.getSalerPromoterList(param);
        if (null != salerPromoterList && salerPromoterList.size() > 0) {
            for (Map<String, Object> data : salerPromoterList) {
                //  如果用户名称为空则显示用户名称为手机号4位
                if(StringUtils.isEmpty(data.get("customerName"))){
                    if(!StringUtils.isEmpty(data.get("phone"))){
                        String customerPhone = data.get("phone").toString();
                        data.put("customerName","手机尾号"+customerPhone.substring(customerPhone.length()-4)+"用户");
                    }
               }
                if(!StringUtils.isEmpty(data.get("promoterTime"))){
                    data.put("promoterTime",data.get("promoterTime").toString().substring(0,19));
                }
                //可提现金额
                data.put("customerBalance",NumberUtils.fenToYuan(Long.valueOf(data.get("customerBalance").toString())));
                //下级数量
                Integer sonCustomerCount = merchantSalerService.getSonCustomerCountBack(data.get("customerId").toString(), param.get("orgId").toString(),1);
                data.put("sonCustomerCount", sonCustomerCount);

                //下级代理数量
                Integer sonPromoterCount = merchantSalerService.getSonCustomerCountBack(data.get("customerId").toString(), param.get("orgId").toString(),2);
                data.put("sonPromoterCount", sonPromoterCount);

                //累计跨级交易额 2020-05-12
                Long crossUserTotalVolume = merchantSalerService.getCrossUserTotalVolume(data.get("customerId").toString(),null,null);
                data.put("crossUserTotalVolume", NumberUtils.fenToYuan(crossUserTotalVolume));
                Long crossUserTotalVolumeSection = merchantSalerService.getCrossUserTotalVolume(data.get("customerId").toString(),param.get("startTime").toString(),param.get("endTime").toString());
                data.put("crossUserTotalVolumeSection", NumberUtils.fenToYuan(crossUserTotalVolumeSection));

                //返润金额 商品推荐费和商品服务费的总和
                Long totalBackFee = merchantInfoService.getTotalBackFee(data.get("customerId").toString(), param.get("orgId").toString());
                data.put("backFee", NumberUtils.fenToYuan(totalBackFee));

                //提现金额
                Long userTotalCash = merchantInfoService.getUserTotalCash(data.get("customerId").toString(), param.get("orgId").toString());
//                Long userTotalFailCash = merchantInfoService.getUserTotalFailCash(data.get("customerId").toString(), orgId);
                data.put("getCash", NumberUtils.fenToYuan(userTotalCash));

                //累计下级交易额(所有用户，不分角色)
                Long userTotalVolumeMoney = merchantSalerService.getUserTotalVolume(data.get("customerId").toString(),1,param.get("orgId").toString(),null,null);
                data.put("allSonVolume", NumberUtils.fenToYuan(userTotalVolumeMoney));

                //区间下级交易额(所有用户，不分角色)
                Long userTotalVolumeSection = merchantSalerService.getUserTotalVolume(data.get("customerId").toString(),1,param.get("orgId").toString(),param.get("startTime").toString(),param.get("endTime").toString());
                data.put("allSonVolumeSection", NumberUtils.fenToYuan(userTotalVolumeSection));

                //累计下级代理交易额(代理用户)
                Long promoterTotalVolume = merchantSalerService.getUserTotalVolume(data.get("customerId").toString(),2,param.get("orgId").toString(),null,null);
                data.put("promoterVolume", NumberUtils.fenToYuan(promoterTotalVolume));

                //区间下级代理交易额(代理用户)
                Long promoterTotalVolumeSection = merchantSalerService.getUserTotalVolume(data.get("customerId").toString(),2,param.get("orgId").toString(),param.get("startTime").toString(),param.get("endTime").toString());
                data.put("promoterVolumeSection", NumberUtils.fenToYuan(promoterTotalVolumeSection));

                //累计推广订单数
                Integer orderCount = merchantSalerService.getOrderCount(data.get("customerId").toString(),param.get("orgId").toString());
                data.put("orderCount", orderCount);

                //结算中
                Long settleFee = merchantSalerService.getSettleFee(data.get("customerId").toString());
                data.put("settleFee", NumberUtils.fenToYuan(settleFee));
            }
        }
        return salerPromoterList;
    }

    @GetMapping("/exportsalerpromotersonlist")
    public void exportSalerPromoterSonList(@RequestParam(value = "customerId", defaultValue = "") String customerId,
                                           @RequestParam(value = "name", defaultValue = "", required = false) String name,
                                           @RequestParam(value = "phone", defaultValue = "", required = false) String phone,
                                           @RequestParam(value = "ifPromoter", defaultValue = "") String ifPromoter,
                                           @RequestParam(value = "startTime", defaultValue = "", required = false) String startTime,
                                           @RequestParam(value = "endTime", defaultValue = "", required = false) String endTime,
                                           HttpServletRequest request, HttpServletResponse response) throws Exception {
        if (StringUtils.isEmpty(customerId) || StringUtils.isEmpty(ifPromoter)) {
            throw GlobalException.build("参数错误");
        }
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        String orgId = userinfo.getOrgId();
        Map<String,Object> param = new HashMap<>();
        param.put("name",name);
        param.put("phone",phone);
        param.put("ifPromoter",ifPromoter);
        param.put("startTime",startTime);
        param.put("endTime",endTime);
        param.put("customerId",customerId);
        param.put("orgId",orgId);
        List<Map<String, Object>> customerSonList = merchantSalerService.getCustomerSonList(param);
        if (null != customerSonList && customerSonList.size() > 0) {
            for (Map<String, Object> data : customerSonList) {
                if(!StringUtils.isEmpty(data.get("parentSaveTime"))){
                    data.put("parentSaveTime",data.get("parentSaveTime").toString().substring(0,19));
                }
                data.put("pCustomerId",customerId);
                data.put("ifPromoter","否");//是否代理
                if("promoter".equals(data.get("customerType").toString()) && "0".equals(data.get("customerType").toString())){
                    data.put("ifPromoter","是");
                }
                //累计返润金额
                Long totalBackFee = merchantInfoService.getSonTotalBackFee(customerId, data.get("customerId").toString(), orgId);
                data.put("backFee", NumberUtils.fenToYuan(totalBackFee));
                //结算中
                Long settleFee = merchantSalerService.getSonSettleFee(data);
                data.put("settleFee", NumberUtils.fenToYuan(settleFee));
                //累计交易额
                Long sonTotalVolume = merchantSalerService.getSonTotalVolume(data);
                data.put("totalFee", NumberUtils.fenToYuan(sonTotalVolume));
            }
        }
        String[] key = {"customerName","phone","parentSaveTime","ifPromoter","backFee","settleFee","totalFee"};
        String[] title = {"昵称","手机号","绑定时间","是否代理","累计返润金额（元）","结算中（元）","累计交易额（元）"};
        String fileName = "下级用户数据";
        commonsService.excelDownload(customerSonList,key,title,fileName,response);
    }

    //加盟代理-下级列表
    @GetMapping("/getsalerpromotersonlist")
    public PageInfo getSalerPromoterSonList(@RequestParam(value = "pageIndex", defaultValue = "1", required = false) int pageIndex,
                                            @RequestParam(value = "pageSize", defaultValue = "10", required = false) int pageSize,
                                            @RequestParam(value = "customerId", defaultValue = "") String customerId,
                                            @RequestParam(value = "name", defaultValue = "", required = false) String name,
                                            @RequestParam(value = "phone", defaultValue = "", required = false) String phone,
                                            @RequestParam(value = "ifPromoter", defaultValue = "") String ifPromoter,
                                            @RequestParam(value = "startTime", defaultValue = "", required = false) String startTime,
                                            @RequestParam(value = "endTime", defaultValue = "", required = false) String endTime,
                                            HttpServletRequest request) throws GlobalException {
        if (StringUtils.isEmpty(customerId) || StringUtils.isEmpty(ifPromoter)) {
            throw GlobalException.build("参数错误");
        }
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        PageHelper.startPage(pageIndex, pageSize);
        String orgId = userinfo.getOrgId();

        Map<String,Object> param = new HashMap<>();
        param.put("name",name);
        param.put("phone",phone);
        param.put("ifPromoter",ifPromoter);
        param.put("startTime",startTime);
        param.put("endTime",endTime);
        param.put("customerId",customerId);
        param.put("orgId",orgId);

        List<Map<String, Object>> customerSonList = merchantSalerService.getCustomerSonList(param);
        if (null != customerSonList && customerSonList.size() > 0) {
            for (Map<String, Object> data : customerSonList) {
                if(!StringUtils.isEmpty(data.get("parentSaveTime"))){
                    data.put("parentSaveTime",data.get("parentSaveTime").toString().substring(0,19));
                }
                data.put("pCustomerId",customerId);
                data.put("ifPromoter","否");//是否代理
                if("promoter".equals(data.get("customerType").toString()) && "0".equals(data.get("promoterStatus").toString())){
                    data.put("ifPromoter","是");
                }
                //累计返润金额
                Long totalBackFee = merchantInfoService.getSonTotalBackFee(customerId, data.get("customerId").toString(), orgId);
                data.put("backFee", NumberUtils.fenToYuan(totalBackFee));
                //结算中
                Long settleFee = merchantSalerService.getSonSettleFee(data);
                data.put("settleFee", NumberUtils.fenToYuan(settleFee));
                //累计交易额
                Long sonTotalVolume = merchantSalerService.getSonTotalVolume(data);
                data.put("totalFee", NumberUtils.fenToYuan(sonTotalVolume));
            }
        }
//        assert customerSonList != null;
        return new PageInfo<>(customerSonList);
    }

    @GetMapping("/getsalerpromotersonbilllist")
    public PageInfo getSalerPromoterSonBillList(@RequestParam(value = "pageIndex", defaultValue = "1", required = false) int pageIndex,
                                            @RequestParam(value = "pageSize", defaultValue = "10", required = false) int pageSize,
                                            @RequestParam(value = "customerId", defaultValue = "") String customerId,
                                            @RequestParam(value = "pcustomerId", defaultValue = "") String pcustomerId
                                                ){
        if(StringUtils.isEmpty(customerId) || StringUtils.isEmpty(pcustomerId)){
            throw GlobalException.build("参数错误");
        }
        PageHelper.startPage(pageIndex, pageSize);
        List<Map<String, Object>> CustomerSonBillList = merchantSalerService.getSalerPromoterSonBillList(pcustomerId,customerId);
        return new PageInfo<>(CustomerSonBillList);
    }

    //加盟代理详情
    @GetMapping("/getpromoterdetail")
    public Map<String,Object> getPromoterDetail(@RequestParam(value = "customerId", defaultValue = "") String customerId,HttpServletRequest request){
        if(StringUtils.isEmpty(customerId)){
            throw GlobalException.build("参数错误");
        }
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        Map<String,Object> param = new HashMap<>();
        param.put("customerId",customerId);
        param.put("orgId",userinfo.getOrgId());
        return merchantSalerService.getPromoterDetail(param);
    }

    //加盟代理详情-业绩列表
    @GetMapping("/getachievelist")
    public PageInfo getAchieveList(@RequestParam(value = "pageIndex", defaultValue = "1", required = false) int pageIndex,
                                   @RequestParam(value = "pageSize", defaultValue = "10", required = false) int pageSize,
                                   @RequestParam(value = "customerId", defaultValue = "") String customerId,
                                   @RequestParam(value = "startTime", defaultValue = "") String startTime,
                                   @RequestParam(value = "endTime", defaultValue = "") String endTime,
                                   HttpServletRequest request){
        if(StringUtils.isEmpty(customerId) || StringUtils.isEmpty(startTime) || StringUtils.isEmpty(endTime)){
            throw GlobalException.build("参数错误");
        }
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        PageHelper.startPage(pageIndex, pageSize);
        Map<String,Object> param = new HashMap<>();
        param.put("customerId",customerId);
        param.put("startTime",startTime);
        param.put("endTime",endTime);
        param.put("orgId",userinfo.getOrgId());
        return new PageInfo<>(merchantSalerService.getAchieveList(param));
    }

    @GetMapping("/getbilllist")
    public PageInfo getBillList(@RequestParam(value = "pageIndex", defaultValue = "1", required = false) int pageIndex,
                                @RequestParam(value = "pageSize", defaultValue = "10", required = false) int pageSize,
                                @RequestParam(value = "customerId", defaultValue = "", required = true) String customerId) throws GlobalException {
        if (StringUtils.isEmpty(customerId)) {
            throw GlobalException.build("参数错误");
        }
        PageHelper.startPage(pageIndex, pageSize);
        return new PageInfo<>(merchantWalletService.detailList(customerId));
    }

    /**
     * 账单明细-详情
     */
    @GetMapping("/getbilldetail")
    public Map<String, Object> getDetail(HttpServletRequest request, @RequestParam(value = "tradeId", defaultValue = "0") Integer tradeId) throws GlobalException {
        if (0 == tradeId) {
            throw GlobalException.build("参数错误");
        }
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        String orgId = userinfo.getOrgId();
        Boolean ifSales = userinfo.getSaler();//是否是小b
        String userId;
        String adminId = userinfo.getAdminId();
        String dongCustomerId = xbMerchantService.getDongCustomerIdByUserId(adminId);
        // 懂小姐对账单详情业务处理
        if (ifSales) {
            userId = merchantInfoService.getCustomerIdByAdminId(adminId);
        } else if (!StringUtils.isEmpty(dongCustomerId)) {
            userId = dongCustomerId;
        } else {
            userId = orgId;
        }
        Map<String, Object> param = new HashMap<>();
        param.put("tradeId", tradeId);
        param.put("orgId", orgId);
        Map<String, Object> finalData = new HashMap<>();
        Map<String, Object> tradeBaseInfo = merchantInfoService.getTradeBaseInfo(param);
        Map<String, Object> inComeData = new HashMap<>();//入账信息
        Map<String, Object> billData = new HashMap<>();//订单信息
        Map<String, Object> moneyList = new HashMap<>();//相关费用清单
        if (null != tradeBaseInfo) {
            int type = (int) tradeBaseInfo.get("type");
            boolean dong = type > 30;
            String orderSn = tradeBaseInfo.get("orderSn").toString();
            String tradeOrgId = tradeBaseInfo.get("orgId").toString();
            inComeData.put("typeInfo", tradeBaseInfo.get("typeInfo"));//类型
            inComeData.put("createTime", tradeBaseInfo.get("createTime"));//入账时间
            inComeData.put("orderTime", tradeBaseInfo.get("orderTime"));//下单时间
            inComeData.put("orderSn", tradeBaseInfo.get("orderSn"));//业务单号
            inComeData.put("busiSn", tradeBaseInfo.get("busiSn"));//行为单号
            inComeData.put("receiveUser", "店铺收支");//入账账户
            inComeData.put("payType", "");//支付类型
            if (!dong) {
                if (!StringUtils.isEmpty(userId) && userId.equals(tradeBaseInfo.get("payUser"))) {
                    inComeData.put("payType", "支出");//支付类型
                }
                if (!StringUtils.isEmpty(userId) && userId.equals(tradeBaseInfo.get("receiveUser"))) {
                    inComeData.put("payType", "收入");//支付类型
                }
            } else {
                if (type == 32|| type == 34 || type ==35 || type == 40) {
                    inComeData.put("payType", "支出");//支付类型
                } else {
                    inComeData.put("payType", "收入");//支付类型
                }
            }

            String amount = NumberUtils.fenToYuan(Long.valueOf(tradeBaseInfo.get("amount").toString()));
            inComeData.put("amount", amount);//金额

            Map<String, Object> orderInfo = merchantInfoService.getOrderInfoByOrderSn(tradeBaseInfo.get("orderSn").toString());
            Object tmpAmount = orderInfo.get("dealAmount");
            String dealAmount = "0";
            if (null != tmpAmount) {
                dealAmount = tmpAmount.toString();
            }
            if ("goods".equals(orderInfo.get("orderFlag"))) {
                billData.put("dealName", orderInfo.get("dealName"));
                if (null != orderInfo.get("dealFrom")) {
                    String[] dealFroms = orderInfo.get("dealFrom").toString().split(",");
                    String tmpFrom = "";
                    for (String from : dealFroms) {
                        String dealFrom = "";
                        if ("-a".equals(from)) {//如果没有belong_id取大麦店铺名称
                            dealFrom = merchantInfoService.storeName(orderInfo.get("orgId").toString());
                        } else {//如果有belong_id取联盟商家的店铺名称
                            dealFrom = merchantInfoService.customerStoreName(orderInfo.get("orgId").toString(), from);
                        }
                        if (tmpFrom.length() == 0) {
                            tmpFrom = dealFrom;
                        } else {
                            tmpFrom = tmpFrom + "," + dealFrom;
                        }
                    }
                    if (StringUtils.isEmpty(tmpFrom)) {
                        String[] dealNames = orderInfo.get("dealName").toString().split(",");
                        String nullFrom = "";
                        for (String name : dealNames) {
                            if (nullFrom.length() == 0) {
                                nullFrom = " ";
                            } else {
                                nullFrom = nullFrom + "," + " ";
                            }
                        }
                        billData.put("dealFrom", nullFrom);
                    } else {
                        billData.put("dealFrom", tmpFrom);
                    }
                } else {
                    billData.put("dealFrom", "");
                }
                billData.put("dealPersonName", orderInfo.get("dealPersonName"));
                billData.put("dealPerson", orderInfo.get("dealPerson"));
                billData.put("dealChannel", orderInfo.get("dealChannel"));

                billData.put("dealAmount", NumberUtils.fenToYuan(Long.valueOf(dealAmount)));
                billData.put("dealSerial", orderInfo.get("dealSerial"));
            }
            if ("saler".equals(orderInfo.get("orderFlag"))) {
                billData.put("dealName", orderInfo.get("dealName"));
                billData.put("dealFrom", merchantInfoService.storeName(orderInfo.get("orgId").toString()));
                billData.put("dealPersonName", orderInfo.get("dealPersonName"));
                billData.put("dealPerson", orderInfo.get("dealPerson"));
                billData.put("dealChannel", orderInfo.get("dealChannel"));
                billData.put("dealAmount", NumberUtils.fenToYuan(Long.valueOf(dealAmount)));
                billData.put("dealSerial", orderInfo.get("dealSerial"));
            }
            if ("enroll".equals(orderInfo.get("orderFlag")) || "vip".equals(orderInfo.get("orderFlag"))) {
                billData.put("dealName", orderInfo.get("dealName"));
                billData.put("dealFrom", merchantInfoService.storeName(orderInfo.get("orgId").toString()));
                billData.put("dealPersonName", orderInfo.get("dealPersonName"));
                billData.put("dealPerson", orderInfo.get("dealPerson"));
                billData.put("dealChannel", orderInfo.get("dealChannel"));
                billData.put("dealAmount", NumberUtils.fenToYuan(Long.valueOf(dealAmount)));
                billData.put("dealSerial", orderInfo.get("dealSerial"));
            }
            if (dong) {
                List<Integer> noPay = Arrays.asList(32, 34, 35 ,40);
                billData.put("dealName", tradeBaseInfo.get("typeInfo"));
                String orgName = merchantInfoService.getOrgName(orgId);
                billData.put("dealFrom", orgName);
                String tradeUserId = noPay.contains(type) ? (String) tradeBaseInfo.get("receiveUser") : (String) tradeBaseInfo.get("payUser");
                String customerPhone = merchantInfoService.getDongCustomerPhoneByCustomerId(tradeUserId);
                billData.put("dealPerson", customerPhone);
                billData.put("dealChannel", noPay.contains(type) ? "-" : "微信支付");
                billData.put("dealAmount", amount);
                billData.put("dealSerial", tradeBaseInfo.get("serialNo"));
            }

            moneyList.put("goodsInCome", merchantInfoService.getEveryMoney(tradeOrgId, orderSn, TradeTypeConstants.DEAL_FEE,userId,ifSales));
            moneyList.put("lhPercentage", merchantInfoService.getEveryMoney(tradeOrgId, orderSn, TradeTypeConstants.GOODS_LINK_PLATFORM_FEE,userId,ifSales));
            moneyList.put("orgPercentage", merchantInfoService.getEveryMoney(tradeOrgId, orderSn, TradeTypeConstants.GOODS_PLATFORM_FEE,userId,ifSales));
            moneyList.put("serviceFee", merchantInfoService.getEveryMoney(tradeOrgId, orderSn, TradeTypeConstants.SERVER_FEE,userId,ifSales));
            moneyList.put("recommendFee", merchantInfoService.getEveryMoney(tradeOrgId, orderSn, TradeTypeConstants.RECOMMENDS_FEE,userId,ifSales));
            moneyList.put("openRoleFee", merchantInfoService.getEveryMoney(tradeOrgId, orderSn, TradeTypeConstants.OPEN_DEAL_FEE,userId,ifSales));
            moneyList.put("spreadFee", merchantInfoService.getEveryMoney(tradeOrgId, orderSn, TradeTypeConstants.SPREAD_FEE,userId,ifSales));
            moneyList.put("tradeServerFee", merchantInfoService.getEveryMoney(tradeOrgId, orderSn, TradeTypeConstants.TRADE_SERVER_FEE,userId,ifSales));
//            moneyList.put("createFee", merchantInfoService.getEveryMoney(tradeOrgId, orderSn, TradeTypeConstants.CREATE_FEE,userId,ifSales));
            moneyList.put("rejuvenateFee", merchantInfoService.getEveryMoney(tradeOrgId, orderSn, TradeTypeConstants.REJUVENATE_FEE,userId,ifSales));
            moneyList.put("purchaseFee", merchantInfoService.getEveryMoney(tradeOrgId, orderSn, TradeTypeConstants.PURCHASE_FEE,userId,ifSales));
            moneyList.put("paycentageFee", merchantInfoService.getEveryMoney(tradeOrgId, orderSn, TradeTypeConstants.PAY_CENTAGE_FEE,userId,ifSales));
            moneyList.put("vipFee", merchantInfoService.getEveryMoney(tradeOrgId, orderSn, TradeTypeConstants.VIP_FEE,userId,ifSales));
            if (dong) {
                moneyList.put("dong", amount);
            }
        }
        finalData.put("inComeData", inComeData);
        finalData.put("billData", billData);
        finalData.put("moneyList", moneyList);
        return finalData;

    }

//    public static void main(String[] args) {
//        String[] dealFroms = ",1".split(",");
//        for (int i = 0; i < dealFroms.length; i++) {
//            System.out.println(dealFroms[i]+"--");
//        }
//    }

    /**
     * 获取钱包余额 小b 大麦 通用
     *
     * @return
     */
    @GetMapping("/getwallet")
    public Map<String, Object> getWallet(HttpServletRequest request) throws Exception {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        String adminId = userinfo.getAdminId();
        String orgId = userinfo.getOrgId();
        Boolean ifSaler = userinfo.getSaler();

        Map<String, Object> record = merchantInfoService.getWallet(adminId, orgId, ifSaler);
        Long balance = (Long) record.getOrDefault("balance", 0L);
        Long freeze = (Long) record.getOrDefault("freeze", 0L);
        Long totalBalance = balance + freeze;
        record.put("totalBalance", NumberUtils.fenToYuan(totalBalance));
        record.put("balance", NumberUtils.fenToYuan(balance));
        record.put("freeze", NumberUtils.fenToYuan(freeze));
        return record;
    }

    /**
     * 审核列表
     *
     * @return
     */
    @GetMapping("/getverifylist")
    public PageInfo<Map<String, Object>> getVerifyList(
            @RequestParam(value = "pageIndex", defaultValue = "1", required = false) int pageIndex,
            @RequestParam(value = "pageSize", defaultValue = "10", required = false) int pageSize,
            HttpServletRequest request
    ) {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        String userType = merchantInfoService.getUserTypeByAdminId(userinfo.getAdminId());
        PageHelper.startPage(pageIndex, pageSize);
        return new PageInfo<>(merchantInfoService.getVerifyList(userinfo.getOrgId(), userType));
    }

    /**
     * 审核详情
     *
     * @return
     */
    @GetMapping("/getverifyinfo")
    public Map<String, Object> getVerifyInfo(
            @RequestParam(required = false) String id,
            @RequestParam(required = false) String customerId
    ) {
        return merchantInfoService.getVerifyInfo(id, customerId);
    }

    /**
     * 审核资质
     *
     * @param params
     * @param session
     * @return
     */
    @PostMapping("/doverifyInfo")
    public Boolean doVerifyInfo(
            @RequestBody Map<String, Object> params,
            HttpServletRequest request
    ) throws Exception {
        if (!params.containsKey("status") || StringUtil.isEmpty(params.get("status").toString())) {
            throw GlobalException.build("参数错误");
        }
        if (!params.containsKey("id") || StringUtil.isEmpty(params.get("id").toString())) {
            throw GlobalException.build("参数错误");
        }
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        String adminId = userinfo.getAdminId();
        String userType = merchantInfoService.getUserTypeByAdminId(adminId);
        params.put("orgId", userinfo.getOrgId());
        params.put("adminId", adminId);
        params.put("userType", userType);
        params.put("status", params.get("status").toString());
        return merchantInfoService.doVerifyInfo(params);
    }

    //获取自动审核开关状态
    @GetMapping("getautocheckstatus")
    public Boolean getAutoCheckStatus(HttpServletRequest request) throws Exception {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        String userType = merchantInfoService.getUserTypeByAdminId(userinfo.getAdminId());
        if (!"1".equals(userType)) {
            throw GlobalException.build("您还不是系统管理员暂无权限");
        }
        return merchantInfoService.getAutoCheckStatus();
    }

    //修改自动审核开关状态
    @PostMapping("changeautocheckstatus")
    public Boolean changeAutoCheckStatus(@RequestBody Map<String, Object> params, HttpServletRequest request) throws Exception {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        String userType = merchantInfoService.getUserTypeByAdminId(userinfo.getAdminId());
        if (!"1".equals(userType)) {
            throw GlobalException.build("您还不是系统管理员暂无权限");
        }
        return merchantInfoService.changeAutoCheckStatus(params);
    }


    /**
     * 关系查询-用户列表
     */
    @GetMapping("/getuserlist")
    public Object getUserList(@RequestParam(value = "pageIndex", defaultValue = "1", required = false) int pageIndex,
                              @RequestParam(value = "pageSize", defaultValue = "10", required = false) int pageSize,
                              @RequestParam(value = "user", defaultValue = "", required = false) String user,
                              @RequestParam(value = "parent", defaultValue = "", required = false) String parent,
                              @RequestParam(value = "startTime", defaultValue = "", required = false) String startTime,
                              @RequestParam(value = "endTime", defaultValue = "", required = false) String endTime,
                              HttpServletRequest request) {

        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        PageHelper.startPage(pageIndex, pageSize);

        Map<String, String> param = new HashMap<String, String>();
        param.put("orgId", userinfo.getOrgId());
        param.put("user",user);
        param.put("parent",parent);
        param.put("startTime",startTime);
        param.put("endTime",endTime);
        List<Map<String, Object>> allUserList = mallBoomBackService.getProUserList(param);
        return new PageInfo<>(allUserList);
    }

    /**
     * 关系查询-用户列表 导出
     */
    @GetMapping("/exportGetuserlist")
    public void exportGetuserlist(
                              @RequestParam(value = "user", defaultValue = "", required = false) String user,
                              @RequestParam(value = "parent", defaultValue = "", required = false) String parent,
                              @RequestParam(value = "startTime", defaultValue = "", required = false) String startTime,
                              @RequestParam(value = "endTime", defaultValue = "", required = false) String endTime,
                              HttpServletRequest request,HttpServletResponse response) throws Exception {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        Map<String, String> param = new HashMap<String, String>();
        param.put("orgId", userinfo.getOrgId());
        param.put("user",user);
        param.put("parent",parent);
        param.put("startTime",startTime);
        param.put("endTime",endTime);
        mallBoomBackService.exportGetuserlist(param, response);
    }

    @PostMapping("/changestatus")
    public void changeStatus(
            @RequestBody Map<String, Object> params
    ) {
        merchantInfoService.changeStatus(params);
    }

    /**
     * 获取 开通加盟代理和推广员 审核开关
     *
     * @param session
     * @return
     */
    @GetMapping("/getcheckswitch")
    public Map<String, Object> getCheckSwitch(HttpServletRequest request) {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        return maiBaoLaService.getCheckSwitch(userinfo.getOrgId());
    }

    /**
     * 审核列表
     *
     * @param pageIndex
     * @param pageSize
     * @param type
     * @param session
     * @return
     */
    @GetMapping("/checklist")
    public PageInfo checkList(
            @RequestParam(value = "pageIndex", defaultValue = "1", required = false) int pageIndex,
            @RequestParam(value = "pageSize", defaultValue = "10", required = false) int pageSize,
            @RequestParam(value = "type") String type,
            HttpServletRequest request
    ) {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        Map<String, Object> params = new HashMap<>();
        params.put("pageIndex", pageIndex);
        params.put("pageSize", pageSize);
        params.put("type", type);

        String orgId = userinfo.getOrgId();
        params.put("orgId", orgId);
        PageHelper.startPage(pageIndex, pageSize);
        return new PageInfo<>(maiBaoLaService.checkList(params));
    }

    /**
     * 审核操作
     *
     * @param params
     * @param session
     */
    @PostMapping("/checkinfo")
    public void checkInfo(
            @RequestBody Map<String, Object> params,
            HttpServletRequest request
    ) {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        params.put("orgId", userinfo.getOrgId());
        maiBaoLaService.checkInfo(params);
    }

    /**
     *获取app关联配置
     *
     * @param session
     */
    @GetMapping("/getAppConfigurateInfo")
    public Map getAppConfigurateInfo(HttpServletRequest request) {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        return maiBaoLaService.getAppConfigurateInfo(userinfo.getOrgId());
    }

    /**
     * 保存app关联配置
     *
     * @param params
     * @param session
     */
    @PostMapping("/saveAppConfigurate")
    public void saveAppConfigurate( @RequestBody Map<String, Object> params,HttpServletRequest request) {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        params.put("orgId", userinfo.getOrgId());
        maiBaoLaService.saveAppConfigurate(params,userinfo.getOrgId());
    }


    //保存自定义海报
    @PostMapping("/savecustomposter")
    public void saveCustomPoster(@RequestBody Map<String, Object> params,HttpServletRequest request){
        if(StringUtils.isEmpty(params.get("posterKey")) || StringUtils.isEmpty(params.get("posterForm")) || StringUtils.isEmpty(params.get("posterType"))){
            throw GlobalException.build("参数错误");
        }
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        String orgId = userinfo.getOrgId();
        params.put("orgId", orgId);
        params.put("posterForm", JSON.toJSONString(params.get("posterForm")));
        boolean ifSaler = userinfo.getSaler();
        String customerId = orgId;
        if (ifSaler) {
            customerId = merchantInfoService.getCustomerIdByAdminId(userinfo.getAdminId());
        }
        params.put("customerId", customerId);
        merchantInfoService.saveCustomPoster(params);
    }

    //自定义海报-列表
    @GetMapping("/getcustomposterlist")
    public List<Map<String, Object>> getCustomPosterList(@RequestParam(value = "posterKey") String posterKey,
                                                         @RequestParam(value = "posterType") String posterType
            ,HttpServletRequest request) {
        if (StringUtils.isEmpty(posterKey) || StringUtils.isEmpty(posterType)) {
            throw GlobalException.build("参数错误");
        }
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        Map<String, Object> params = new HashMap<>();
        String orgId = userinfo.getOrgId();
        params.put("orgId", orgId);
        params.put("posterKey", posterKey);
        params.put("posterType", posterType);
        return merchantSalerService.getCustomPosterList(params);
    }


    //自定义海报-数量
    @GetMapping("/getcustompostercount")
    public Integer getCustomPosterCount(@RequestParam(value = "posterKey") String posterKey,
                                        @RequestParam(value = "posterType") String posterType
            , HttpServletRequest request) {
        if (StringUtils.isEmpty(posterKey) || StringUtils.isEmpty(posterType)) {
            throw GlobalException.build("参数错误");
        }
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        Map<String, Object> params = new HashMap<>();
        String orgId = userinfo.getOrgId();
        params.put("orgId", orgId);
        params.put("posterKey", posterKey);
        params.put("posterType", posterType);
        return merchantInfoService.getCustomPosterCount(params);
    }

    //自定义海报-删除
    @PostMapping("/delcustomposter")
    public void delCustomPoster(@RequestBody Map<String, Object> params, HttpServletRequest request) {
        if (StringUtils.isEmpty(params.get("posterId"))) {
            throw GlobalException.build("参数错误");
        }
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        params.put("orgId", userinfo.getOrgId());
        merchantInfoService.delCustomPoster(params);
    }



}
